package org.cncy;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class HttpsJsonUtil {

    static final String charsetName = "UTF-8";


    public static byte[] getJsonRequestByte(int command,String requestStr) {

        final int PROTOCOL_JSON_VERSION = 2001; // json新协议版本

        byte[] rawRequest = new byte[0];
        try {
            byte[] rawBody = requestStr.getBytes(charsetName);

            rawBody = combineBytes(int2Bytes(rawBody.length), rawBody);

            // 包头：数据段共16个字节，每4个字节为一个字段（低位在前）
            PacketHead head = new PacketHead(PROTOCOL_JSON_VERSION, 0, 0, command);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            baos.write(int2Bytes(head.protocolVer));
            baos.write(int2Bytes(head.isCompress));
            baos.write(int2Bytes(head.encrptType));
            baos.write(int2Bytes(head.commandType));
            byte[] rawHdr = baos.toByteArray();

           // System.out.println(Arrays.toString(rawHdr));
            //System.out.println(Arrays.toString(rawBody));
            rawRequest = combineBytes(rawHdr, rawBody);
           // System.out.println(new String(rawRequest,"UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rawRequest;
    }

    static class PacketHead {
        public int commandType = 0;
        public int encrptType = 0;
        public int isCompress = 0;
        public int protocolVer = 0;

        public PacketHead(int protocolVer, int isCompress, int encrptType, int commandType) {
            this.protocolVer = protocolVer;
            this.isCompress = isCompress;
            this.encrptType = encrptType;
            this.commandType = commandType;
        }
    }

    public static byte[] combineBytes(byte[] byte1, byte[] byte2) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            int count;
            ByteArrayInputStream bins2;
            byte[] buffer2;
            if (byte1 != null) {
                bins2 = new ByteArrayInputStream(byte1);
                buffer2 = new byte[1024];

                while((count = bins2.read(buffer2)) != -1) {
                    baos.write(buffer2, 0, count);
                    baos.flush();
                }
            }

            if (byte2 != null) {
                bins2 = new ByteArrayInputStream(byte2);
                buffer2 = new byte[1024];

                while((count = bins2.read(buffer2)) != -1) {
                    baos.write(buffer2, 0, count);
                    baos.flush();
                }
            }
        } catch (Exception var6) {
            return null;
        }

        return baos.toByteArray();
    }

    public static byte[] int2Bytes(int intValue) {
        byte[] b = new byte[4];

        for(int i = 0; i < 4; ++i) {
            b[i] = (byte)(intValue >> 8 * i & 255);
        }

        return b;
    }

}